"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.JSONToDTSConverter = void 0;
const fs = __importStar(require("fs"));
const path = __importStar(require("path"));
class JSONToDTSConverter {
    constructor(headerText) {
        this.typeMapping = {
            "integer": "number",
            "float": "number",
            "double": "number",
            "boolean": "boolean",
            "string": "string",
            "table": "any",
            "function": "Function",
            "nil": "any"
        };
        // 自定义头部文本
        this.headerText = `
// 类型别名定义
type Fixed = number;

// 类型别名定义
type AbilityKey = number; // 技能编号
type AbilitySlot = number; // 技能槽位
type Achievement = number; // 自定义成就
type AnimKey = number; // 动画编号
type Archive = number; // 自定义存档
type CampID = number; // 阵营ID
type Color = number; // 颜色
type CreatureKey = LifeEntityKey; // 生物编号
type CustomTriggerSpaceID = UnitID; // 触发区域ID
type CustomTriggerSpaceKey = UnitKey; // 触发区域编号
type EButton = ENode; // UI按钮节点
type EImage = ENode; // UI图片节点
type EInputField = ENode; // UI输入节点
type ELabel = ENode; // UI文本节点
type ENode = string; // UI节点
type EProgressbar = ENode; // UI进度条节点
type EmojiKey = number; // 气泡表情编号
type EquipmentID = UnitID; // 物品ID
type EquipmentKey = number; // 物品编号
type EquipmentSlot = number; // 物品槽位
type InteractBtnID = number; // 交互按钮编号
type LifeEntityKey = UnitKey; // 生命体编号
type ModifierKey = number; // 效果编号
type ObstacleID = UnitID; // 组件ID
type ObstacleKey = UnitKey; // 组件编号
type PathID = UnitID; // 路径ID
type PathPointID = UnitID; // 路点ID
type RoleID = number; // 玩家ID
type SfxID = number; // 特效ID
type SfxKey = number; // 特效编号
type SkyBoxBackground = number; // 天空盒背景
type SoundID = number; // 音效ID
type SoundKey = number; // 音效编号
type Timestamp = number; // 时间戳
type TriggerSpaceKey = UnitKey; // 逻辑体编号
type UgcCommodity = number; // 道具
type UgcGoods = string; // 商品
type UnitGroupKey = UnitKey; // 组件组编号
type UnitID = number; // 单位ID
type UnitKey = number; // 单位编号

type AbilityPointerType=number //技能指示器类型

type BattleShopKey= number //商店
type  CharacterKey=LifeEntityKey //角色编号
type CameraShakeType= number //屏幕震动类型
type DamageSchema=number//伤害方案
type DecorationKey = UnitKey; // 装饰物编号

type E3DLayer = string; // 场景UI实例

type E3DLayerKey = number; // 场景UI预设

type EBagSlot = ENode; // UI物品槽位节点

type EEffectNode = ENode; // UI动效节点

type FontKey = number; // 字体key

type ImageKey = number; // 图片编号

type JointAssistantType = number; // 关节类型

type LevelKey = string; // 关卡编号

type MontageKey = string; // 剧情动画编号

type PaintArea = number; // 染色区域

declare class Decoration{}
declare class UnitGroup{}
declare class JointAssistant{}
declare class Timer{}
declare class GoodsInfo{}

`;
        if (headerText) {
            this.headerText = headerText;
        }
    }
    normalizeType(typeName) {
        return this.typeMapping[typeName.toLowerCase()] || typeName;
    }
    parseMethodKey(methodKey) {
        // 支持 . 和 : 作为分隔符
        const parts = methodKey.split(/[.:]/);
        if (parts.length < 2) {
            return { className: "Global", methodName: methodKey };
        }
        const className = parts[0];
        const methodName = parts.slice(1).join('.');
        return { className, methodName };
    }
    generateParamString(params) {
        if (!params || params.length === 0)
            return "";
        return params.map(param => {
            const type = param.typeInfo ? this.normalizeType(param.typeInfo.name) : "any";
            return `${param.name}: ${type}`;
        }).join(', ');
    }
    generateReturnString(returns) {
        if (!returns || returns.length === 0)
            return "void";
        const returnTypes = returns.map(ret => {
            return ret.typeInfo ? this.normalizeType(ret.typeInfo.name) : "any";
        });
        if (returnTypes.length === 1) {
            return returnTypes[0];
        }
        return `[${returnTypes.join(', ')}]`;
    }
    groupMethodsByClass(data) {
        const classMap = {};
        if (!data.classMethods) {
            console.warn("Warning: No 'classmethods' found in JSON data");
            return classMap;
        }
        for (const methodKey in data.classMethods) {
            const { className, methodName } = this.parseMethodKey(methodKey);
            const methodInfo = data.classMethods[methodKey];
            if (!classMap[className]) {
                classMap[className] = {
                    className,
                    methods: {}
                };
            }
            classMap[className].methods[methodName] = methodInfo;
        }
        return classMap;
    }
    generateClassDeclaration(className, methods) {
        const lines = [];
        lines.push(`declare class ${className} {`);
        for (const methodName in methods) {
            const method = methods[methodName];
            const params = this.generateParamString(method.params);
            const returnType = this.generateReturnString(method.returns);
            const staticKeyword = method.isStatic ? "static " : "";
            if (method.description) {
                lines.push(`    /** ${method.description} */`);
            }
            lines.push(`    ${staticKeyword}${methodName}(${params}): ${returnType};`);
        }
        lines.push("}");
        return lines.join('\n');
    }
    generateGlobalFunctions(methods) {
        const lines = [];
        for (const methodName in methods) {
            const method = methods[methodName];
            const params = this.generateParamString(method.params);
            const returnType = this.generateReturnString(method.returns);
            if (method.description) {
                lines.push(`/** ${method.description} */`);
            }
            lines.push(`declare function ${methodName}(${params}): ${returnType};`);
        }
        return lines.join('\n');
    }
    generateEventEnum(events) {
        const lines = [];
        const enumMap = {};
        // 解析事件值并分组
        for (const eventKey in events) {
            const eventInfo = events[eventKey];
            let enumName = eventKey;
            let enumValue = eventInfo.value;
            // 尝试从键名中提取枚举名
            const parts = eventKey.split('.');
            if (parts.length > 1) {
                enumName = parts[parts.length - 1];
            }
            // 清理事件值（移除多余的引号）
            if (enumValue.startsWith('"') && enumValue.endsWith('"')) {
                enumValue = enumValue.slice(1, -1);
            }
            if (enumValue.startsWith("'") && enumValue.endsWith("'")) {
                enumValue = enumValue.slice(1, -1);
            }
            // 确保枚举名唯一
            if (enumMap[enumName]) {
                console.warn(`Duplicate event name: ${enumName}`);
                enumName = `${enumName}_${Object.keys(enumMap).length}`;
            }
            enumMap[enumName] = enumValue;
            // 添加注释
            if (eventInfo.description) {
                lines.push(`    /** ${eventInfo.description} */`);
            }
            // 添加枚举项
            lines.push(`    ${enumName} = "${enumValue}",`);
        }
        if (lines.length === 0)
            return "";
        return `declare enum EVENT {\n${lines.join('\n')}\n}`;
    }
    /**
 * 新增：按枚举名分组枚举值（如将"Enums.AIBasicCommand.JUMP"归到"AIBasicCommand"组）
 */
    groupEnumsByEnumName(enums) {
        const enumGroup = {};
        for (const enumKey in enums) {
            // 拆分枚举键："Enums.AIBasicCommand.JUMP" → ["Enums", "AIBasicCommand", "JUMP"]
            const keyParts = enumKey.split('.');
            if (keyParts.length < 3 || keyParts[0] !== 'Enums') {
                console.warn(`无效的枚举键格式：${enumKey}（需符合"Enums.枚举名.枚举值名"）`);
                continue;
            }
            const enumName = keyParts[1]; // 枚举名：AIBasicCommand
            const enumValueName = keyParts[2]; // 枚举值名：JUMP
            const enumItem = enums[enumKey];
            // 初始化枚举组（如首次处理AIBasicCommand时创建分组）
            if (!enumGroup[enumName]) {
                enumGroup[enumName] = {};
            }
            enumGroup[enumName][enumValueName] = enumItem;
        }
        return enumGroup;
    }
    /**
     * 生成枚举声明（格式：declare namespace Enums { enum 枚举名 { ... } }）
     */
    generateEnumDeclarations(enums) {
        if (!enums || Object.keys(enums).length === 0)
            return "";
        const enumGroup = this.groupEnumsByEnumName(enums);
        const enumLines = [];
        // 命名空间开始
        enumLines.push("declare namespace Enums {");
        // 遍历每个枚举组，生成命名空间内的enum
        for (const enumName in enumGroup) {
            const enumValues = enumGroup[enumName];
            enumLines.push(`    enum ${enumName} {`); // 缩进对齐
            // 遍历枚举值，生成枚举项（含注释）
            for (const valueName in enumValues) {
                const item = enumValues[valueName];
                // 处理描述注释
                if (item.description) {
                    enumLines.push(`        /** ${item.description} */`); // 二级缩进
                }
                // 处理枚举值（数字/字符串）
                const enumValue = typeof item.value === 'string'
                    ? `"${item.value.replace(/["']/g, '')}"`
                    : item.value;
                enumLines.push(`        ${valueName} = ${enumValue},`); // 二级缩进
            }
            enumLines.push("    }"); // 闭合单个enum
            enumLines.push(""); // 枚举间空行分隔
        }
        // 命名空间结束
        enumLines.push("}");
        return enumLines.join('\n');
    }
    convert(data) {
        const output = [];
        // 添加自定义头部文本
        output.push(this.headerText);
        output.push("");
        // 处理事件枚举
        if (data.events && Object.keys(data.events).length > 0) {
            output.push(this.generateEventEnum(data.events));
            output.push("");
        }
        // 新增：处理enums枚举（生成declare enum）
        if (data.enums && Object.keys(data.enums).length > 0) {
            output.push(this.generateEnumDeclarations(data.enums));
            output.push("");
        }
        // 处理类方法
        if (data.classMethods) {
            const classMap = this.groupMethodsByClass(data);
            // 处理全局函数
            if (classMap.Global) {
                output.push(this.generateGlobalFunctions(classMap.Global.methods));
                delete classMap.Global;
            }
            // 处理类
            for (const className in classMap) {
                output.push(this.generateClassDeclaration(className, classMap[className].methods));
                output.push("");
            }
        }
        return output.join('\n');
    }
    convertFromFile(inputPath) {
        if (!fs.existsSync(inputPath)) {
            throw new Error(`Input file not found: ${inputPath}`);
        }
        const content = fs.readFileSync(inputPath, 'utf-8');
        return JSON.parse(content);
    }
    convertToDTS(inputPath, outputPath) {
        const data = this.convertFromFile(inputPath);
        const dtsContent = this.convert(data);
        // 确保输出目录存在
        const outputDir = path.dirname(outputPath);
        if (!fs.existsSync(outputDir)) {
            fs.mkdirSync(outputDir, { recursive: true });
        }
        fs.writeFileSync(outputPath, dtsContent, 'utf-8');
    }
    convertDirectory(inputDir, outputDir, pattern = /\.json$/) {
        if (!fs.existsSync(inputDir)) {
            throw new Error(`Input directory not found: ${inputDir}`);
        }
        if (!fs.existsSync(outputDir)) {
            fs.mkdirSync(outputDir, { recursive: true });
        }
        const files = fs.readdirSync(inputDir);
        for (const file of files) {
            if (pattern.test(file)) {
                const inputPath = path.join(inputDir, file);
                const outputPath = path.join(outputDir, file.replace(pattern, '.d.ts'));
                try {
                    this.convertToDTS(inputPath, outputPath);
                    console.log(`Converted: ${file} -> ${path.basename(outputPath)}`);
                }
                catch (error) {
                    console.error(`Error converting ${file}:`, error.message);
                }
            }
        }
    }
}
exports.JSONToDTSConverter = JSONToDTSConverter;
// 使用示例
function main() {
    // 自定义头部文本
    const customHeader = `// =============================================
// Auto-generated TypeScript declaration file
// Generated from JSON documentation
// Date: ${new Date().toISOString()}
// =============================================
`;
    const converter = new JSONToDTSConverter(customHeader);
    // 示例JSON数据（包含类方法和事件）
    const sampleJson = {
        classMethods: {
            "Camp:get_roles": {
                "params": [
                    {
                        "name": "_score",
                        "typeInfo": {
                            "name": "integer",
                            "description": "",
                            "lineNumber": 1726
                        },
                        "description": "积分",
                        "fieldType": "param",
                        "value": null,
                        "deprecated": null,
                        "see": []
                    }
                ],
                "returns": [],
                "description": "设置阵营积分",
                "lineNumber": 1723,
                "isStatic": true,
                "deprecated": null,
                "see": []
            },
            "Camp.add_member": {
                "params": [
                    {
                        "name": "player_id",
                        "typeInfo": {
                            "name": "string",
                            "description": "",
                            "lineNumber": 1730
                        },
                        "description": "玩家ID",
                        "fieldType": "param",
                        "value": null,
                        "deprecated": null,
                        "see": []
                    }
                ],
                "returns": [
                    {
                        "typeInfo": {
                            "name": "boolean",
                            "description": "",
                            "lineNumber": 1732
                        },
                        "description": "是否添加成功"
                    }
                ],
                "description": "添加阵营成员",
                "lineNumber": 1728,
                "isStatic": false,
                "deprecated": null,
                "see": []
            }
        },
        events: {
            "EVENT.ABILITY_SWITCH_OUT": {
                "description": "技能切出 事件主体 Ability 技能 事件回调参数 ability Ability 触发技能 事件回调参数 unit Unit 技能拥有者 事件回调参数 switch_in_ability Ability 切换后的技能",
                "value": "\"ABILITY_SWITCH_OUT\"",
                "deprecated": null,
                "see": []
            },
            "EVENT.UNIT_ATTACKED": {
                "description": "单位被攻击事件",
                "value": "\"UNIT_ATTACKED\"",
                "deprecated": null,
                "see": []
            }
        }
    };
    // 直接转换JSON对象
    console.log("Direct conversion result:");
    console.log(converter.convert(sampleJson));
    // 保存为文件
    const tempInputPath = path.join(__dirname, 'temp.json');
    const outputPath = path.join(__dirname, 'output.d.ts');
    try {
        fs.writeFileSync(tempInputPath, JSON.stringify(sampleJson, null, 2), 'utf-8');
        converter.convertToDTS(tempInputPath, outputPath);
        console.log(`File saved to: ${outputPath}`);
        // 检查文件内容
        const fileContent = fs.readFileSync(outputPath, 'utf-8');
        console.log("File content:");
        console.log(fileContent);
    }
    catch (error) {
        console.error("Error during file conversion:", error);
    }
    finally {
        // 清理临时文件
        if (fs.existsSync(tempInputPath)) {
            fs.unlinkSync(tempInputPath);
        }
    }
    // 转换整个目录
    const inputDir = path.join(__dirname, 'json-docs');
    const outputDir = path.join(__dirname, 'dts-files');
    try {
        if (!fs.existsSync(inputDir))
            fs.mkdirSync(inputDir, { recursive: true });
        if (!fs.existsSync(outputDir))
            fs.mkdirSync(outputDir, { recursive: true });
        // 创建示例文件
        const sampleFilePath = path.join(inputDir, 'sample.json');
        fs.writeFileSync(sampleFilePath, JSON.stringify(sampleJson, null, 2), 'utf-8');
        // 转换目录
        converter.convertDirectory(inputDir, outputDir);
        console.log(`Directory converted: ${inputDir} -> ${outputDir}`);
    }
    catch (error) {
        console.error("Error during directory conversion:", error);
    }
}
// 如果直接运行此文件，执行示例
if (require.main === module) {
    main();
}
